package com.mm.seguridad.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomSecurityFilter extends GenericFilterBean {



    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        SecurityContextHolder.setContext(loadSecurityContext(request));
        chain.doFilter(request, response);
    }

    /**
     * Get the proper security context. If a crowd token is found, create a CrowdTokenSecurityContext and use this as the current security context.
     * Otherwise use the current security context.
     *
     * @param request HttpServletRequest
     * @return A SecurityContext
     */
    private SecurityContext loadSecurityContext(HttpServletRequest request) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        String token = "";
        if (StringUtils.isNotEmpty(token)) {
            try {
                System.out.println("here");
//                CrowdUserDetails crowdUserDetails = userDetailService.loadUserByToken(token);
//                Authentication crowdAuthentication = new CrowdSSOAuthenticationToken(crowdUserDetails, token, crowdUserDetails.getAuthorities());
//                securityContext = new CrowdTokenSecurityContext(crowdAuthentication);
            } catch (DataAccessException ex) {
                logger.info("The CrowdTokenAuthenticationFilter failed to verify the token provided.");
            }
        }
        return securityContext;
    }

}